//
//  MHComposeViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/11/6.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHComposeViewController.h"
#import "MHComposeViewModel.h"
#import "MHComposeHeaderView.h"
#import "MHPhotoManager.h"
#import "SharePopView.h"
#import "MHLocationTipsView.h"
#import "MHLocationViewModel.h"
#import "MHCommonArrowItemViewModel.h"
#import "MHSettingRedPacketViewModel.h"
#import "MHCommonCell.h"
#import "MHRedPacketCreateModel.h"
#import "MHFinishComposeAlert.h"
#import "MHPurseInfo.h"
#import "YYTextView+MHExtension.h"
@interface MHComposeViewController ()<UIGestureRecognizerDelegate,YYTextViewDelegate>

@property(nonatomic, strong)  MHComposeViewModel *viewModel;
@property(nonatomic, strong) MHComposeHeaderView *headerView;

//@property(nonatomic, strong) MHRedPacketCreateModel *redPacketCreateModel;
@end

@implementation MHComposeViewController
@dynamic viewModel;

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self setupNav];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGuesture:)];
    tap.delegate = self;
    tap.cancelsTouchesInView = false;
    [self.view addGestureRecognizer:tap];
    [self startLacation];
    [self.headerView.textView resignFirstResponder];
   

}



-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)handleGuesture:(UITapGestureRecognizer *)sender {
    CGPoint point = [sender locationInView:self.headerView.textView];
    if(![self.headerView.textView.layer containsPoint:point]) {
        [self.headerView.textView resignFirstResponder];
    }else
    {
        [self.headerView.textView becomeFirstResponder];
    }
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isKindOfClass:[YYTextView class]]) {
        return NO;
    }
    return YES;
}

-(void) startLacation
{
    __weak __typeof(self)weakSelf = self;
    [[MHLocationManager sharedInstance] startUpdatingLocationWithBlock:^(CLLocation *location){
        [[MHLocationManager sharedInstance] searhAroundWithLocation:location reslutBlock:^(AMapPOISearchBaseRequest *requst,AMapPOISearchResponse *response) {
            if (response.pois.count > 0) {
                AMapPOI *currentPOI =  response.pois.firstObject;
                MHCustomTip *tip =  [MHCustomTip createWithAMapPOI:currentPOI];
                weakSelf.viewModel.circleLocation = tip.circleLocation;
                [weakSelf.tableView reloadData];
            }
        }];
        [MHLocationManager uploadLocationToRemote:location];
    }];
    
    [MHLocationManager sharedInstance].delegate = self;
    
    if (![MHLocationManager isLocationServiceOpen]) {
        [self configCirclePositon];
    }
}

-(void) configCirclePositon
{
    if (self.viewModel.model.location ) {
        self.viewModel.circleLocation = self.viewModel.model.location;
    }
}

- (void)configureCell:(MHCommonCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    
    
    cell.textLabel.textColor = MHMetionTextColor;
    cell.detailTextLabel.textColor = MHTextColor333;
    
    MHCommonArrowItemViewModel *item = object;
    if (self.viewModel.circleLocation && indexPath.row == 0) {
        item.subtitle = self.viewModel.circleLocation.isShowLocation ? self.viewModel.circleLocation.areaName : @"不显示位置";
    }
    
    if (indexPath.row == 1) {
        [self congfigItem:item];
    }

    [super configureCell:cell atIndexPath:indexPath withObject:object];
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
}


-(void) congfigItem:(MHCommonArrowItemViewModel *) item
{
    if (self.viewModel.redPacketCreateModel) {
        switch (self.viewModel.redPacketCreateModel.type) {
            case RedPacketInCircle:
                item.icon = @"ic_theme_qn";
                item.subtitle = @"圈内红包";
                break;
            case RedPacketNearby:
                item.icon = @"ic_theme_fj";
                item.subtitle = @"附近红包";
                break;
            case RedPacketShare:
                item.icon = @"ic_theme_fx";
                item.subtitle = @"微信红包";
                break;
                
            default:
                item.icon = @"ic_theme_qn";
                item.subtitle = @"圈内红包";
                break;
        }
    }else
    {
        item.icon = @"ic_theme_package_n";
        item.subtitle = @"";
    }
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

-(void)setupNav {
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem mh_customItemWithTitle:@"取消" titleColor:nil imageName:nil target:self selector:@selector(dissMiss) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];;
    self.navigationItem.rightBarButtonItem =   [UIBarButtonItem mh_customItemWithTitle:@"发送" titleColor:nil imageName:nil target:self selector:@selector(send) contentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    NSString *circleName = self.viewModel.model.title;
    NSString *prefix = @"发送至";
    

    if (circleName) {
        UILabel *titleView = [[UILabel alloc]init];
        titleView.height = 100;
        titleView.width = 200;
        titleView.numberOfLines = 0;
        titleView.textAlignment = NSTextAlignmentCenter;
        titleView.y = 50;
        NSString *str = [NSString stringWithFormat:@"%@\n%@", prefix, circleName];
        // 创建一个带有属性的字符串（比如颜色属性、字体属性等文字属性）
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:str];
        [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:[str rangeOfString:prefix]];
        [attStr addAttribute:NSForegroundColorAttributeName value:MHTextColor333 range:[str rangeOfString:prefix]];
        [attStr addAttribute:NSFontAttributeName value:MHRegularFont_12 range:[str rangeOfString:circleName]];
        [attStr addAttribute:NSForegroundColorAttributeName value:MHTextColorF75 range:[str rangeOfString:circleName]];
        titleView.attributedText = attStr;
        self.navigationItem.titleView = titleView;
    }else{
        self.title = prefix;
    }

}

- (BOOL)textView:(YYTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (self.viewModel.type == MHCirclComposeTypeVideo) {
        return [textView textView:textView shouldChangeTextInRange:range replacementText:text maxLength:55];
    }else
    {
        return YES;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSArray *arr = @[@"圈内红包",@"附近红包",@"微信红包"];
    if (indexPath.row == 1) {
        if (self.viewModel.redPacketCreateModel) {
            MHSettingRedPacketViewModel *createModel = [[MHSettingRedPacketViewModel alloc] initWithServices:self.viewModel.services params:nil];
            createModel.location = self.viewModel.circleLocation;
            createModel.type = self.viewModel.redPacketCreateModel.type;
            createModel.createModel = self.viewModel.redPacketCreateModel;
//            createModel.
            createModel.title = arr[createModel.type - 1];
            @weakify(self);
            [[createModel.finishSubject deliverOnMainThread] subscribeNext:^(MHRedPacketCreateModel *createModel) {
                @strongify(self);
                self.viewModel.redPacketCreateModel = createModel;
                [self.tableView reloadData];
            }];
            [self.viewModel.services pushViewModel:createModel animated:YES];
        }else
        {
            SharePopView *popView =  [[SharePopView alloc] initWithNameArr:@[@"圈内红包",@"附近红包",@"微信红包"] iconsNames:@[@"ic_package_qn",@"ic_package_fj",@"ic_package_fx"] containerHeight:180 itemHeight:120 showHeader:NO headerText:nil];
            __weak __typeof(self)weakSelf = self;
            __weak __typeof(popView) weakPopView = popView;
            popView.circleBottonCilckBlock = ^(int index) {
                
                if (index == 1 && (weakSelf.viewModel.circleLocation == nil || !weakSelf.viewModel.circleLocation.isShowLocation)) {
                    [UIWindow showTips:@"请您先选择位置"];
                    return ;
                }
                [weakPopView dismiss];
                MHSettingRedPacketViewModel *createModel = [[MHSettingRedPacketViewModel alloc] initWithServices:weakSelf.viewModel.services params:nil];
                createModel.title = arr[index];
                createModel.type = index + 1;
                createModel.location = weakSelf.viewModel.circleLocation;
//                @weakify(self);
                [[createModel.finishSubject deliverOnMainThread] subscribeNext:^(MHRedPacketCreateModel *createModel) {
//                    @strongify(self);
                    weakSelf.viewModel.redPacketCreateModel = createModel;
                    [weakSelf.tableView reloadData];
                }];
                [weakSelf.viewModel.services pushViewModel:createModel animated:YES];
            };
            [popView show];
        }
        
    }else
        
    {
        __weak __typeof(self)weakSelf = self;
            if (![MHLocationManager isLocationServiceOpen]) {
                MHLocationTipsView *locationView = [MHLocationTipsView mh_viewFromXib];
                weakSelf.zh_popupController = [zhPopupController new];
                //        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
                locationView.width = self.view.mh_width * 0.7;
                locationView.layer.cornerRadius = 8.0;
                locationView.masksToBounds = YES;
                [weakSelf.zh_popupController presentContentView:locationView];
                //        locationView.settingButton.rac_command = self.viewModel.nextCommand;
                __weak __typeof(self)weakSelf = self;
                [locationView.startLocation bk_whenTapped:^{
                    [[MHLocationManager sharedInstance] openLocationSetting];
                    [weakSelf.zh_popupController dismiss];
                }];
                //                [weakSelf.textView resignFirstResponder];
                [locationView.dissBtn bk_whenTapped:^{
                    
                    [weakSelf.zh_popupController dismiss];
                }];
            }else
            {
                MHLocationViewModel *locationModel = [[MHLocationViewModel alloc] initWithServices:self.viewModel.services params:self.viewModel.model.location ? @{MHViewModelUtilKey:self.viewModel.model.location} : nil ];
                locationModel.isRecentLocation = YES;
                [self.viewModel.services pushViewModel:locationModel animated:YES];
                locationModel.completeBlock = ^(MHCustomTip *tip) {
                    
//                    weakSelf.locationIndicateView.locationLabel.text = !tip.isShowLocation ? @"不显示位置" : tip.name;
                    if (tip.isShowLocation) {
                        weakSelf.viewModel.circleLocation = tip.circleLocation;
                    }else
                    {
                        weakSelf.viewModel.circleLocation = tip.circleLocation;
                    }
                    [weakSelf.tableView reloadData];
                };
            }
            
//        }]
    }
    
}




-(void) dissMiss
{
    [self.viewModel.closeCommand execute:nil];
}

-(void)send {


    if (self.headerView.textView.text.length <= 0) {
        [MBProgressHUD mh_showTips:@"请输入内容"];
        return;
    }
    if (self.viewModel.selectPhotos.count <= 0    ) {
        [UIWindow showTips:@"请选择一张照片图片或照片"];
        return;
    }
    
    [self.headerView.textView resignFirstResponder];
    if (self.headerView.textView.fullText.length > 55 && self.viewModel.type == MHCirclComposeTypeVideo) {
        [UIWindow showTips:@"最多不超过55个字"];
        return;
    }
    
    if(self.viewModel.redPacketCreateModel)
    {
        [self showPopView];
    }else
    {
           [self sendWithImage];
    }

}

- (void)sendWithImage
{
    

    
    
    self.navigationItem.rightBarButtonItem.enabled =  NO;
    
    if (self.viewModel.redPacketCreateModel != nil) {
        __weak __typeof(self)weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.navigationItem.rightBarButtonItem.enabled = YES;
        });
    }
    
    NSString *preRedPacket = @"";
    if (self.viewModel.redPacketCreateModel) {
        if (self.viewModel.redPacketCreateModel.type == RedPacketInCircle) {
            preRedPacket = @"#圈内红包#";
        }else if(self.viewModel.redPacketCreateModel.type == RedPacketNearby)
        {
            preRedPacket = @"#附近红包#";
        }else if(self.viewModel.redPacketCreateModel.type == RedPacketShare)
        {
            preRedPacket = @"#微信红包#";
        }
    }
   
    self.viewModel.content =  [NSString stringWithFormat:@"%@%@",preRedPacket,self.headerView.textView.fullText];
    [[self.viewModel.uploadCommand execute:self.viewModel.selectPhotos] subscribeNext:^(id x) {

    } error:^(NSError *error) {

    } completed:^{

    }];

}

-(void) showPopView
{
    MHFinishComposeAlert *composeAlertView = [MHFinishComposeAlert mh_viewFromXib];
    self.zh_popupController = [zhPopupController new];
    composeAlertView.width = MH_SCREEN_WIDTH * 0.8;
    composeAlertView.layer.cornerRadius = 8.0;
    composeAlertView.masksToBounds = YES;
    composeAlertView.priceLabel.text = FormatFloatToString(self.viewModel.redPacketCreateModel.amount);
    [self.zh_popupController presentContentView:composeAlertView];
    __weak __typeof(self)weakSelf = self;
    [composeAlertView.comfirmBtn bk_whenTapped:^{
        [weakSelf.zh_popupController dismiss];
        [weakSelf sendWithImage];
    }];
    @weakify(self);
    
    [[[[MHHTTPService sharedInstance] getUserPurseInfo] mh_parsedResults] subscribeNext:^(MHPurseInfo *info) {
        @strongify(self);
        composeAlertView.leftAmountLabel.text = [NSString stringWithFormat:@"剩余￥%@",FormatFloatToString(info.canTxMoney)] ;
        if (info.canTxMoney >= self.viewModel.redPacketCreateModel.amount) {
             composeAlertView.leftButton.selected = YES;
            weakSelf.viewModel.redPacketCreateModel.payType  =  MHCircleComposePayTypeLeft;
        }else
        {
            composeAlertView.topView.userInteractionEnabled = false;
            composeAlertView.timeButton.selected = YES;
            weakSelf.viewModel.redPacketCreateModel.payType  =  MHCircleComposePayTypeWX;
        }
    }];
    

   
    [composeAlertView.topView bk_whenTapped:^{
        composeAlertView.leftButton.selected = YES;
        composeAlertView.timeButton.selected = NO;
        weakSelf.viewModel.redPacketCreateModel.payType  =  MHCircleComposePayTypeLeft;
    }];
    
    [composeAlertView.bottomView bk_whenTapped:^{
        composeAlertView.leftButton.selected = NO;
        composeAlertView.timeButton.selected = YES;
        weakSelf.viewModel.redPacketCreateModel.payType  =  MHCircleComposePayTypeWX;
    }];
    
}

-(void)openCamera {
  self.viewModel.selectPhotos =   [MHPhotoManager selectedAlbumPhotosIncludingGifWithPHAssets:nil photos:self.viewModel.selectPhotos];
}


-(void) reloadHeaderPic
{
    NSMutableArray *datas =   [self.viewModel.selectPhotos mutableCopy];
    if (self.viewModel.selectPhotos.count < 9 && ( self.viewModel.type != MHCirclComposeTypeAsk)) {
        UIImage *addImage = [UIImage imageNamed:@"ic_theme_addphoto"];
        MHUploadImage *image = [MHUploadImage new];
        image.image = addImage;
        image.isGif = false;
        image.hiddenDel = YES;
        [datas appendObject:image];
    }else if(self.viewModel.selectPhotos.count ==  0 && ( self.viewModel.type == MHCirclComposeTypeAsk))
    {
        UIImage *addImage = [UIImage imageNamed:@"ic_theme_addphoto"];
        MHUploadImage *image = [MHUploadImage new];
        image.image = addImage;
        image.isGif = false;
        image.hiddenDel = YES;
        [datas appendObject:image];
    }
    int rows =  datas.count/3  + ((datas.count %3 == 0) ? 0: 1);
     CGFloat picHeight = 50 + rows * 103 + (rows -1) *10;
    if (self.viewModel.type != MHCirclComposeTypeVideo) {
        [self.headerView.selectPicView.collectionView setContentSize:CGSizeMake(MH_SCREEN_WIDTH, picHeight)];
        [self.headerView.selectPicView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.headerView);
            make.height.equalTo(@(picHeight));
        }];
        [self.headerView.selectPicView.dataSource reloadWithItems:datas];
    }
//    [self.tableView reloadData];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (!self.headerView) {
        NSMutableArray *datas =   [self.viewModel.selectPhotos mutableCopy];
        
        
        MHComposeHeaderView *compsoeHeaderView = [[MHComposeHeaderView alloc] initWithFrame:CGRectMake(0, 0, MH_SCREEN_WIDTH, 400) type:self.viewModel.type];
        self.headerView = compsoeHeaderView;
    }
    
    __weak __typeof(self)weakSelf = self;
    self.headerView.openCameraBlock = ^{
        [weakSelf openCameraIsPublish:(weakSelf.viewModel.type == MHCirclComposeTypePublish) selectedAssets:weakSelf.viewModel.selectAsserts completionBlock:^(NSArray *photos,NSArray *assert) {
            weakSelf.viewModel.selectPhotos = [photos mutableCopy];
            weakSelf.viewModel.selectAsserts = assert;
            [weakSelf reloadHeaderPic];
        }];
    };
     self.headerView.textView.delegate = self;
    
    MHUploadImage *uploadVideo = self.viewModel.selectPhotos.firstObject;
    self.headerView.videoView.coverView.image = uploadVideo.image;
    self.headerView.videoView.redPacketBtn.hidden = YES;
    self.headerView.deletePohotoBlock = ^(int item) {
        [weakSelf.viewModel.selectPhotos removeObjectAtIndex:item];
        NSMutableArray *array = [weakSelf.viewModel.selectAsserts mutableCopy];
         [array removeObjectAtIndex:item];
        weakSelf.viewModel.selectAsserts = [array copy];
        [weakSelf reloadHeaderPic];
    };
    
    [self reloadHeaderPic];
    [self.headerView setNeedsLayout];
    [self.headerView layoutIfNeeded];
    return self.headerView;
    
}

-(void)openCameraIsPublish:(BOOL) isPublish selectedAssets:(NSArray *)selecatedAssets completionBlock:(VoidBlock_id_id)completionBlock  {
    [MHPhotoManager fetchPhotosFromAlbum:self maxImagesCount:isPublish?9:1 allowCrop:NO selectedAssets:selecatedAssets completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        NSMutableArray *photesArray =  [MHPhotoManager selectedAlbumPhotosIncludingGifWithPHAssets:assets photos:photos];
        completionBlock(photesArray,assets);
    } cancel:^{
        
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    NSMutableArray *datas =   [self.viewModel.selectPhotos mutableCopy];
//    int rows =  datas.count/3  + ((datas.count %3 == 0) ? 0: 1);
//    CGFloat picHeight = 50 + rows * 103 + (rows -1) *10;
//    return  picHeight + 200;
    return 470;
}


@end
